package com.zh.note.demo.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhanghuan
 * @date: 2023/4/6 20:43
 * @description: create it
 */
public class FooBar {
    private int n;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    int singal = 1;


    public FooBar(int n) {
        this.n = n;
    }

    public void foo() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                while (singal != 1) {
                    condition1.await();
                }
                System.out.println("foo");
                singal = 2;
                condition2.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }


        }
    }

    public void bar() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                while (singal != 2) {
                    condition2.await();
                }
                System.out.println("bar");
                singal = 1;
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }


        }
    }

    public static void main(String[] args) {
        FooBar fooBar = new FooBar(2);
        new Thread(() -> {
            try {
                fooBar.foo();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "1").start();

        new Thread(() -> {
            try {
                fooBar.bar();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "2").start();

    }
}